<template>
  <div class="order-list">
    <div class="d-flex a-center j-sb box-header">
      <el-form :model="filterForm" :inline="true" ref="filterData">
        <el-form-item label="订单编号：">
          <el-input placeholder="请输入订单编号" v-model="filterForm.orderNo"></el-input>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="filterForm.placeTime"
            type="daterange"
            align="right"
            unlink-panels
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-button type="primary" style="margin:0 10px" @click="filterData()">查询</el-button>
        <el-button type="primary" @click="filterData(0)">全部</el-button>
        <el-button type="primary" @click="filterData(1)">待付款</el-button>
        <el-button type="primary" @click="filterData(3)">待配药</el-button>
        <el-button type="primary" @click="filterData(6)">待取药</el-button>
        <el-button type="primary" @click="filterData(7)">已完成</el-button>
        <el-button type="primary" @click="filterData(5)">已关闭</el-button>
      </el-form>
      <el-button type="success" @click="exportData">导出</el-button>
    </div>
    <div class="mt-2" v-if="tableData">
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        highlight-current-row
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        @selection-change="selectionChange"
      >
        <el-table-column type="selection" min-width="5" align="center"></el-table-column>
        <el-table-column prop="orderNo" min-width="8" label="订单编号" align="center"></el-table-column>
        <el-table-column prop="buyingTime" min-width="8" label="下单时间" align="center"></el-table-column>
        <el-table-column prop="createBy" min-width="5" label="用户账号" align="center"></el-table-column>
        <el-table-column prop="medicalCodeJson" min-width="12" label="购买商品" align="center">
            <template slot-scope="scope">
                <div style="height:50px;width:200px;overflow:hidden">
                    <div class="item" v-for="(item,index) in scope.row.medicalList" :key="index" style="height:50px;width:150px;display:flex;justify-content: space-around;align-items: center;">
                        <div style="width:60px;height:40px">
                            <img v-if="item.medicalImage.length" style="width:60px;height:40px" :src="item.medicalImage[0].imgUrl" alt="">
                        </div>
                        <div>{{item.medicalName}}</div>
                    </div>
                </div>
            </template>
        </el-table-column>
        <el-table-column prop="total" min-width="8" label="订单金额(元)" align="center"></el-table-column>
        <el-table-column prop="payMethod" min-width="8" label="支付方式" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.payMethod==1">微信支付</span>
            <span v-else-if="scope.row.payMethod==2">电子凭证支付</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" min-width="5" label="订单状态" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.status==1">未支付</span>
            <span v-else-if="scope.row.status==2">支付中</span>
            <span v-else-if="scope.row.status==3">支付成功(待配药)</span>
            <span v-else-if="scope.row.status==4">支付失败</span>
            <span v-else-if="scope.row.status==5">取消支付</span>
            <span v-else-if="scope.row.status==6">待取药(配药完成)</span>
            <span v-else-if="scope.row.status==7">订单完成(已取药)</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="seeOrderDetail(scope.row)">查看订单</el-button>
            <el-button v-if="scope.row.status==1" size="mini" type="warning" @click="changState(scope.row)">{{operationText}}</el-button>
            <el-button v-else size="mini" type="info" disabled @click="changState(scope.row)">{{operationText}}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="float: right;padding:5px;margin-top:10px;"
        small
        @current-change="currentChange"
        :current-page="currentPage"
        :pageSize="pageSize"
        :total="total"
        layout="total, prev, pager, next"
      ></el-pagination>
    </div>
    <el-dialog
      title="订单详情"
      :visible.sync="dialogVisible"
      width="50%"
      top="30px"
      @close="dialogClose"
    >
      <el-steps :active="ativtedNum" simple>
        <el-step v-for="(item, index) in stepList" :key="index" :title="item"></el-step>
      </el-steps>
      <div class="d-flex a-center text-center ml-3 mt-2" style="color:#888">
        <div class="span-12 d-felx a-center j-center flex-column">
          <div class="mb-1">下单时间</div>
          <div>{{dialogObj.buyingTime}}</div>
        </div>
        <div class="span-12 d-felx a-center j-center flex-column">
          <div class="mb-1">付款时间</div>
          <div>{{dialogObj.paySuccessTime}}</div>
        </div>
      </div>
      <div style="background:#f7f7f7;border-radius:10rpx" class="p-2 my-2">
        <div class="pb-1">当前订单状态：
            <span v-if="dialogObj.status==1">未支付</span>
            <span v-else-if="dialogObj.status==2">支付中</span>
            <span v-else-if="dialogObj.status==3">支付成功</span>
            <span v-else-if="dialogObj.status==4">支付失败</span>
            <span v-else-if="dialogObj.status==5">取消支付</span>
            <span v-else-if="dialogObj.status==6">订单完成(已取药)</span>
        </div>
        <div v-if="dialogObj.status==1">
          买家还有
          <span style="color:#ffc63b;margin:0 2px">{{countDown}}</span>支付订单,否则系统将自动关闭订单。
          <br />如果药品被恶意拍下, 您可以点击下方按钮关闭订单。
          <br />
          <el-button style="margin-top:20px" type="danger" @click="closeOrder">关闭订单</el-button>
        </div>
      </div>
      <div class="px-2 mb-2">
        <p class="font-weight font-md py-1">配药信息</p>
        <p class="py">配药医师：<span  v-if="dialogObj.pharmacist">{{dialogObj.pharmacist}}</span><span style="color:#DFB240;" v-else>请先配药</span></p>
        <p class="py">配药时间：<span v-if="dialogObj.pharmacistDate">{{dialogObj.pharmacistDate}}</span><span style="color:#DFB240;" v-else>请先配药</span></p>
        <el-button v-if="dialogObj.status==3" type="primary" style="margin-top:20px" @click="FillImmediately">立即配药</el-button>
        <p class="py" v-else-if="dialogObj.status==6" style="color:green">配药完成</p>
      </div>
      <div class="px-2 mb-2">
        <p class="font-weight font-md py-1">取药信息</p>
        <p class="py">取药地址：{{dialogObj.drugAddress}}</p>
        <p class="py">客户备注：{{dialogObj.remark?dialogObj.remark:'无'}}</p>
        <el-button v-if="dialogObj.status==6" type="primary" style="margin-top:20px" @click="getMedical">立即取药</el-button>
        <p class="py" v-else-if="dialogObj.status==7" style="color:green">取药完成</p>
      </div>
      <div class="px-2 mb-2">
        <p class="font-weight font-md py-1">订单信息</p>
        <p class="py">订单编号：{{dialogObj.orderNo}}</p>
        <el-table
          :data="dialogObj.medicalList"
          border
          style="width: 100%"
          highlight-current-row
          :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        >
          <el-table-column prop="medicalCode" min-width="10" label="药品编码" align="center"></el-table-column>
          <el-table-column prop="medicalName" min-width="10" label="药品通用名" align="center"></el-table-column>
          <el-table-column prop="medicalSpecifications" min-width="5" label="规格" align="center"></el-table-column>
          <el-table-column prop="medicalDosageForm" min-width="5" label="剂型" align="center"></el-table-column>
          <el-table-column prop="medicalUnit" min-width="5" label="单位" align="center"></el-table-column>
          <el-table-column prop="amount" min-width="5" label="数量" align="center"></el-table-column>
          <el-table-column prop="medicalActivePrice" min-width="5" label="售价(元)" align="center"></el-table-column>
        </el-table>
      </div>
      <el-dialog
        width="30%"
        title="配药信息"
        :visible.sync="innerVisible"
        append-to-body>
         <el-form
          :inline="true"
          label-position="right"
            label-width="140px"
          :model="formData"
          class="demo-form-inline"
          :rules="rules"
          ref="roleForm"
        >
          <el-form-item label="配药医师" prop="pharmacist">
            <el-input v-model="formData.pharmacist" placeholder="输入配药医师姓名"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="text-center">
          <el-button style="margin-right:20px" @click="innerVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogVisibleTrue">保 存</el-button>
        </div>
      </el-dialog>
       <el-dialog
        width="30%"
        title="取药验证码"
        :visible.sync="innerVisible2"
        append-to-body>
         <el-form
          :inline="true"
          label-position="right"
            label-width="140px"
          :model="formdata"
          class="demo-form-inline"
          :rules="rule"
          ref="getMedForm"
        >
          <el-form-item label="取药验证" prop="takeCode">
            <el-input v-model="formdata.takeCode" placeholder="输入四位取药码"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="text-center">
          <el-button style="margin-right:20px" @click="innerVisible2 = false">取 消</el-button>
          <el-button type="primary" @click="innerVisibleTrue">保 存</el-button>
        </div>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import { formatTimeToStr } from "@/util/date";
export default {
  data() {
    const codeRule = (rule, value, callBack) => {
            if (!this.formdata.takeCode) {
                return callBack(new Error("请输入取药码"));
            }else if(this.formdata.takeCode!=this.dialogObj.takeCode){
              return callBack(new Error("请输入正确的取药码"));
            }else{
               return callBack()
            }
    };
    return {
      status:0,//查询状态
      filterForm: {},
      tableData: [],
      currentPage: 1,
      ativtedNum:1,
      pageSize: 10,
      total: 0,
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      operationText: "关闭订单",
      dialogVisible: false,
      innerVisible:false,
      innerVisible2:false,
      stepList: ["买家下单", "买家付款",],
      selectionData: [],
      stateText: "待付款",
      stateDesc: "药品已拍下, 等待买家付款",
      countDown: "",
      timer: "",
      orderNo:'',
      startBuyingTime:'',
      endBuyingTime:'',
      dialogObj:{},
      formData:{pharmacistDate:'1',pharmacist:'',status:'6'},
      rules:{
         pharmacist: [{ required: true, message: "请填写配药医师姓名", trigger: "blur" }],
      },
      formdata:{},
       rule:{
         takeCode: [{ validator:codeRule, trigger: "blur" }],
      },
    };
  },
  created() {
    this.getOrder();
  },
  methods: {
    //订单查询
    filterData(num){
      if(!isNaN(num)){
        this.orderNo=''
        this.startBuyingTime=''
        this.endBuyingTime=''
        this.filterForm={}
        this.status=num
        this.getOrder()
      }else{
        this.orderNo=this.filterForm.orderNo?this.filterForm.orderNo:''
        this.startBuyingTime =this.filterForm.placeTime?formatTimeToStr(this.filterForm.placeTime[0], "yyyy-MM-dd hh:mm:ss"):''
        this.endBuyingTime = this.filterForm.placeTime?formatTimeToStr(this.filterForm.placeTime[1], "yyyy-MM-dd hh:mm:ss"):''
        console.log(this.orderNo)
        this.getOrder()
      }
    },
    //关闭订单
    changState(){
      
    },
    //立即取药
    getMedical(){
      this.innerVisible2=true
    },
    innerVisibleTrue(){
      this.$refs['getMedForm'].validate(valid => {
          if (valid) {
            this.post(
              "/orderMerchant/edit",
              {id:this.dialogObj.id,status:'7'},
              res => {
                this.$message.success("取药成功");
                 this.post('/orderMerchant/getOrder',{drugCode:this.dialogObj.drugCode,id:this.dialogObj.id},res=>{
                  console.log(res.data.status)
                  Object.assign(this.dialogObj,{status:res.data[0].status})
                },false)
                this.innerVisible2=false
                this.formdata={}
              },
              false
            );
          }
        });
    },
    //立即配药
    FillImmediately(){
      this.formData={pharmacistDate:'1',pharmacist:'',status:'6'}
      this.innerVisible=true
      if(this.dialogObj.pharmacist){
        this.formData.pharmacist=this.dialogObj.pharmacist
      }
    },
    dialogVisibleTrue(){
       this.$refs['roleForm'].validate(valid => {
          if (valid) {
            Object.assign(this.formData,{id:this.dialogObj.id})
            this.post(
              "/orderMerchant/edit",
              this.formData,
              res => {
                this.$message.success("配药成功");
                this.post('/orderMerchant/getOrder',{drugCode:this.dialogObj.drugCode,id:this.dialogObj.id},res=>{
                  Object.assign(this.dialogObj,{pharmacist:res.data[0].pharmacist,pharmacistDate:res.data[0].pharmacistDate})
                  this.dialogObj.status=res.data[0].status
                },false)
                this.innerVisible=false
              },
              false
            );
          }
        });
    },
    //查询订单
    getOrder() {
      this.post(
        "/orderMerchant/getOrder",
        { pageSize: this.pageSize, pageNum: this.currentPage,status:this.status?this.status:'',orderNo:this.orderNo,startBuyingTime:this.startBuyingTime,endBuyingTime:this.endBuyingTime},
        res => {
          if (res.code == 200) {
            this.tableData = res.data.list;
            this.total = res.data.total;
          }
        },
        false
      );
    },
    selectionChange(val) {
      this.selectionData = val;
    },
    exportData() {},
    getStateText(state) {
      if (state == 1) {
        return "待付款";
      } else if (state == 3) {
        return "待配药";
      } else if (state == 4) {
      }
    },
    currentChange(val) {
      this.currentPage = val;
      this.getOrder()
    },
    seeOrderDetail(row) {
      console.log(row)
      this.dialogObj=row
      if(this.dialogObj.status==1||this.dialogObj.status==4||this.dialogObj.status==5){
        this.ativtedNum=1
      }else{
        this.ativtedNum=2
      }
      this.dialogVisible = true;
      if(row.status==1){
        this.post('/orderMerchant/getSurplusTime',{orderNo:row.orderNo},res=>{
          if(res.code==200){
              this._setInterval(res.data);
          }
       },false)
      }
    },
    changState(row) {

    },
    closeOrder() {

    },
    dialogClose() {
      clearInterval(this.timer);
      this.getOrder()
    },
    _setInterval(targetStamp) {
      let stamp = parseInt(targetStamp);
      let minutes, seconds;
      this.timer = setInterval(() => {
        if (stamp > 0) {
          stamp -= 1;
          minutes = parseInt(stamp / 60);
          seconds = parseInt(stamp % 60);
          minutes = minutes < 10 ? "0" + minutes : minutes;
          seconds = seconds < 10 ? "0" + seconds : seconds;
          this.countDown = minutes + ":" + seconds;
        } else {
          clearInterval(this.timer);
          stamp = 0;
          this.countDown = "00:00";
        }
      }, 1000);
    },
    getData() {}
  }
};
</script>

<style scoped>
.order-list /deep/ .el-form-item {
  margin-bottom: 0;
}
</style>